Vue Js Download Text on Click:To enable downloading text on click in Vue.js, you can create a function that generates a text file and triggers its download. First, import the required dependencies. Then, create a function that accepts the text content as a parameter. Inside the function, create a new Blob object with the text content and set the file type to “text/plain”. Next, create a temporary anchor element, set its download attribute to the desired file name, and append it to the document body. Finally, simulate a click on the anchor element and remove it from the DOM. This allows users to download the text file when they click a specific element in the Vue.js app.
How can I implement a functionality in Vue js to download text when a button is clicked?
This code snippet demonstrates how to implement a functionality in Vue.js that allows users to download the text content of a textarea upon clicking a button.
The Vue instance defines a textarea with its content bound to the textareaContent
data property. The downloadText
method is triggered by the button’s click event.
Inside the method, the text content is obtained from the textarea, and a Blob object is created using the content. A temporary <a>
element is created, and its href
is set to the Blob URL. The download
attribute specifies the desired file name. Programmatically clicking the link triggers the download. Finally, the temporary URL is revoked after a short delay.
Vue Js Download Text on Click Example
<div id="app">
<textarea v-model="textareaContent"></textarea>
<button @click="downloadText">Download Text</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
textareaContent: 'Vue.js is a progressive JavaScript framework for building user interfaces. It allows developers to create dynamic and interactive web applications by combining declarative templates, component-based architecture, and reactive data binding. Vue.js is lightweight, flexible, and easy to integrate with existing projects.' // Default textarea content
};
},
methods: {
downloadText() {
const text = this.textareaContent; // Get the content from the textarea
// Create a new Blob object with the text content
const blob = new Blob([text], { type: 'text/plain' });
// Create a temporary <a> element and set its download attribute to specify the file name
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'file.txt'; // Replace with your desired file name
// Programmatically click the link to trigger the download
link.click();
// Clean up the URL.createObjectURL by revoking the object URL after some time
setTimeout(() => {
URL.revokeObjectURL(link.href);
}, 100);
}
}
});
</script>